package com.galengao.springboot.eventlistener.controller;

import com.galengao.springboot.eventlistener.dto.UserDto;
import com.galengao.springboot.eventlistener.service.UserService;
import com.galengao.springboot.validateAndResponse.resp.BaseResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.List;

/**
 * 用户控制器
 *
 * @author galenGao
 * @version Id: UserController.java, v 0.1 2022/7/21 21:00  GalenGao Exp $$
 */
@RestController
@RequestMapping("/user")
@RequiredArgsConstructor
public class UserController {

    private final UserService userService;

    @PostMapping("/register")
    public BaseResponse<String> register(@Valid @RequestBody UserDto userDto, BindingResult bindingResult) {
        List<FieldError> fieldErrors = bindingResult.getFieldErrors();
        if (!CollectionUtils.isEmpty(fieldErrors)) {
            String defaultMessage = fieldErrors.get(0).getDefaultMessage();
            return BaseResponse.fail(defaultMessage, 500);
        }
        return userService.register(userDto);
    }
}
